package cn.bdqn.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.bdqn.pojo.Goods;
import cn.bdqn.service.GoodsService;
import cn.bdqn.util.ExportExcelUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.List;

@Controller
public class ExcelController {

    @Resource
    private GoodsService goodsService;

    /**
     * 跳转到主页
     */
    @GetMapping("/index")
    public String put(){
        return "index";
    }

    /**
     * 导出
     */
    @GetMapping("/export")
    public void  ExportBankCkeckInfo(HttpServletResponse response){
        //得到所有要导出的数据
        List<Goods> orderlist =goodsService.exportExcel();
        //定义导出的excel名字
        String excelName = "商品表";
        //获取需要转出的excel表头的map字段
        LinkedHashMap<String, String> fieldMap = new LinkedHashMap<>();
        //设置数据库表的列名和excel表格的标题列的映射关系
        fieldMap.put("id","编号");
        fieldMap.put("name","商品名称");
        fieldMap.put("price","商品价格");
        fieldMap.put("count","商品库存");
        fieldMap.put("type","商品类型");
        //导出用户相关信息
        new ExportExcelUtils().export(excelName,orderlist,fieldMap,response);
    }

    /**
     * 导入
     */
    @PostMapping("/import")
    @ResponseBody
    public String importExcel(@RequestParam("file") MultipartFile file) throws Exception{
        ImportParams params = new ImportParams();
        params.setTitleRows(0);
        params.setHeadRows(1);
        InputStream inputStream = file.getInputStream();
        List<Goods> list = ExcelImportUtil.importExcel(inputStream,
                Goods.class, params);
        goodsService.importExcel(list);
        inputStream.close();
        return "成功";
    }
}

